package com.example.weatherapp1.presentation.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel() {
    // 通用的协程异常处理器
    protected val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
        handleException(throwable)
    }

    // 启动协程并处理异常
    protected fun launchSafe(block: suspend () -> Unit) {
        viewModelScope.launch(coroutineExceptionHandler) {
            block()
        }
    }

    // 异常处理
    protected open fun handleException(throwable: Throwable) {
        // 可以在这里统一处理异常，如记录日志等
        throwable.printStackTrace()
    }
}
